package com.example.demo.Gmail.controller;


import com.example.demo.Gmail.Excutor.ThreadUpload;
import com.example.demo.Gmail.Excutor.WatchUserMailExcutor;
import com.example.demo.Gmail.Handle.proxyHandler;
import com.example.demo.Gmail.model.MessageModel;
import com.example.demo.Gmail.model.UserModel;
import com.example.demo.Gmail.service.BackendService;
import com.example.demo.Gmail.service.UserService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@Component
public class ScheduledExecutor {

    @Autowired
    UserService userService;

     @Autowired
     BackendService backendService;

    private Logger logger = LoggerFactory.getLogger(ScheduledExecutor.class);


    public  Set<String> gmailId( String lableId, UserModel user,Set<String> gmailIds) {
        List lables= Lists.newArrayList();
        lables.add(lableId);
        Set<String> mongoIds=  backendService.messages(lableId,user.getEmailAddress())
                                             .stream()
                                             .map(MessageModel::getMessageId)
                                             .collect(Collectors.toSet());
        if (mongoIds.size()==0){
            return gmailIds;
        }else {
            gmailIds.removeAll(mongoIds);
            return gmailIds;
        }
    }
    public void importGmailToMongo(Set<String> set,String lable,UserModel user) throws GeneralSecurityException, IOException, InterruptedException, ExecutionException {
        set= this.gmailId(lable,user,set);
        List<Callable<MessageModel>> tasks = new ArrayList<>();
        for (String id:set){
            Callable<MessageModel>  upload=   new ThreadUpload(lable,user,id);
            tasks.add(upload);
        }
        List<MessageModel> messageModels = new ArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        List<Future<MessageModel>> futures=executorService.invokeAll(tasks);
        for (Future<MessageModel> future:futures){
            messageModels.add(future.get());
        }
        executorService.shutdown();//关闭线程池
        backendService.insertInbox(messageModels);
    }
    //触发定时任务，变更本地邮箱用户的historyId，每天上午5.00变更
    @Scheduled(cron = "0 0 05 * * ?")
    public void updateHistoryId() throws InterruptedException, ExecutionException {
        //大陆环境需要加代理
        //proxyHandler.proxy();
        List list= Lists.newArrayList();
        list.add("SENT");
        list.add("INBOX");
        List<UserModel> users= userService.users();
        if (users!=null&users.size()!=0){
            List<Callable<UserModel>> tasks = new ArrayList<>();
            for (UserModel user:users){
                Callable<UserModel>  userExcutor=   new WatchUserMailExcutor(user,list);
                tasks.add(userExcutor);
            }
            List<UserModel> userModels = new ArrayList<>();
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            List<Future<UserModel>> futures=executorService.invokeAll(tasks);
            for (Future<UserModel> future:futures){
                userModels.add(future.get());
            }
            executorService.shutdown();//关闭线程池
            userService.updateUser(userModels);
        }
    }

}
